package com.itzg.vboxfarm.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.virtualbox_4_1.IVirtualBox;
import org.virtualbox_4_1.VBoxException;

import com.itzg.vboxfarm.domain.ConnectionStatus;
import com.itzg.vboxfarm.domain.HostMachine;
import com.itzg.vboxfarm.service.bits.HostChangedEvent;

@Component
@Scope("prototype")
public class HostConnectionResolverInstance {

	private static Logger logger = LoggerFactory
			.getLogger(HostConnectionResolverInstance.class);

	@Autowired(required = true)
	HostConfigService hostConfigService;

	@Autowired
	VirtualBoxManagerService vboxService;

	@Async
	public void resolve(HostMachine hostMachine) {
		logger.debug("Starting host connection resolution for {}", hostMachine);

		try {
			IVirtualBox vbox = vboxService.createConnection(hostMachine);

			logger.debug("Succesfully validated connection to {}", hostMachine);
			hostMachine.setConnectionStatus(ConnectionStatus.VALID);
			hostMachine.setStatusMessage(null);
			hostMachine.setProcessors(vbox.getHost().getProcessorOnlineCount());
			hostMachine.setTotalMemory(vbox.getHost().getMemorySize());
			
			vboxService.releaseConnection(vbox);
			hostConfigService.publishEvent(new HostChangedEvent(this, hostMachine,
					HostChangedEvent.Type.CONNECTED));
			hostConfigService.updateHost(hostMachine);
		} catch (VBoxException e) {
			hostMachine.setConnectionStatus(ConnectionStatus.FAILED);
			hostMachine.setStatusMessage(e.getMessage());
			hostConfigService.updateHost(hostMachine);
		}
	}
}
